package com.bsoft.gol.hcs.his.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.utils.BaseRespUtil;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;
import com.bsoft.gol.hcs.utils.DateUtil;
import com.security.cipher.sm.SM4Utils;
import ctd.access.AccessToken;
import ctd.access.loader.AccessTokenLoader;
import ctd.account.AccountCenter;
import ctd.account.UserRoleToken;
import ctd.account.user.User;
import ctd.controller.exception.ControllerException;
import ctd.net.rpc.Client;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.util.AppContextHolder;
import ctd.util.annotation.RpcService;
import ctd.util.context.Context;
import ctd.util.context.ContextUtils;
import com.bsoft.gol.hcs.enumcase.InterfaceTypeEnum;
import hcn.util.BaseResponse;
import hcn.bean.PushMessageBean;
import com.bsoft.gol.mpi.model.Certificate;
import com.bsoft.gol.mpi.model.Unique;
import com.bsoft.gol.mpi.provider.IMPIProvider;
import com.bsoft.gol.mpi.service.MPIException;
import org.apache.commons.lang3.StringUtils;
import hcn.service.commonClinical.qo.SendMsgCodeRequest;
import hcn.util.IdentityTransformUtil;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.his.bean.request.PushMessageRequest;
import com.bsoft.gol.hcs.his.bean.request.SendMsgRequest;
import com.bsoft.gol.hcs.his.bean.vo.MsgVariable;
import com.bsoft.gol.hcs.his.service.SendMsgService;
import org.atag.util.http.KdHttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import service.rpc.IOrganizationRpcService;
import service.rpc.impl.SmsServiceImpl;
import com.bsoft.gol.hcs.specialist.bean.vo.FollowUpRecordsMessageVO;
import com.bsoft.gol.hcs.specialist.dao.FollowUpRecordsRequisitionDAO;
import com.bsoft.gol.hcs.specialist.entity.FollowUpRecordsRequisition;
import com.bsoft.gol.hcs.specialist.entity.FusTeamChronicGroupRecordEntity;
import org.atag.util.common.RedisUtil;

import java.util.*;

@Service
public class SendMsgServiceImpl implements SendMsgService {
    private final static Logger log = LoggerFactory.getLogger(SendMsgServiceImpl.class);

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SmsServiceImpl smsService;
    @Autowired
    private IOrganizationRpcService organizationRpcService;
    private JSONObject jsonParams;

    @Value("${project_source}")
    private String projectSource;

    @Value("${tenant_id}")
    private String tanlentId;

    @Autowired
    private FollowUpRecordsRequisitionDAO followUpRecordsRequisitionDAO;

    @SsdevReference("mpi.mpiProvider")
    private IMPIProvider mpiProvider;
    @Value("${follow_up_dist_url}")
    private String followUpDistUrl;

    /**
     * @Describe: 推送消息
     * @Param: [pushMessageRequest]
     * @Return: org.atag.core.base.BaseResponse<java.lang.String>
     * @Author: zhengcb10708
     * @Date: 2020/11/9 15:59
     */
    @Override
    public BaseResponse<String> pushNewMessage(PushMessageRequest pushMessageRequest) {
        String url = "";
        log.info("pushNewMessage 进入健康通，推送消息,入参:" + pushMessageRequest.toString());
        if (InterfaceTypeEnum.GOL.getCode().equals(projectSource)) {
            if (CommonUtils.isNotEmpty(pushMessageRequest.getMsgVariableMap())) {
                List<MsgVariable> setMsgVariableList = new ArrayList<>();
                for (Map.Entry<String, String> entry : pushMessageRequest.getMsgVariableMap().entrySet()) {
                    MsgVariable msgVariable = new MsgVariable();
                    msgVariable.setMsgVariableKey(entry.getKey());
                    msgVariable.setMsgVariableValue(entry.getValue());
                    setMsgVariableList.add(msgVariable);
                    pushMessageRequest.setMsgVariableList(setMsgVariableList);
                }
            }
            jsonParams = JSONObject.parseObject(JSONObject.toJSONString(pushMessageRequest));
            url = Constants.GOL_FAMILY_URL + Constants.PUSH_NEWMESSAGE;
        }
        return this.getJsonObject(url, jsonParams);
    }

    @Override
    @Deprecated
    public BaseResponse<String> productionMessage(SendMsgRequest sendMsgRequest) {
        String url = "";
        if (InterfaceTypeEnum.HOL.getCode().equals(projectSource)) {
            jsonParams = JSONObject.parseObject(JSONObject.toJSONString(sendMsgRequest));
            log.info("进入互联网医院，推送消息");
            url = Constants.HOL_FAMILY_URL + Constants.HOL_SEND_MESSAGE;
            if (jsonParams.containsKey("type")) {
                jsonParams.remove("type");
            }
        } else if (InterfaceTypeEnum.GOL.getCode().equals(projectSource)) {
            MsgVariable msgVariable_new = new MsgVariable();
            //todo lin rpc 改造
            log.info("进入健康通，推送消息");
            if (CommonUtils.isNotEmpty(sendMsgRequest.getMobile())) {
                List<MsgVariable> msgVariableList = sendMsgRequest.getMsgVariableList();
                if (CommonUtils.isNotEmpty(msgVariableList)) {
                    for (MsgVariable msgVariable : msgVariableList) {
                        if ("#msgType#".equals(msgVariable.getMsgVariableKey())) {
                            msgVariable_new.setMsgVariableKey(msgVariable.getMsgVariableValue());
                        }
                        if ("#msgContent#".equals(msgVariable.getMsgVariableKey())) {
                            msgVariable_new.setMsgVariableValue(msgVariable.getMsgVariableValue());
                        }
                    }
                    List<MsgVariable> list = new ArrayList<>();
                    list.add(msgVariable_new);
                    sendMsgRequest.setMsgVariableList(list);
                }
            }
            if (CommonUtils.isEmpty(sendMsgRequest.getMsgId())) {
                sendMsgRequest.setMsgId(UUID.randomUUID().toString());
            }
            jsonParams = JSONObject.parseObject(JSONObject.toJSONString(sendMsgRequest));
            url = Constants.GOL_FAMILY_URL + Constants.SEND_MESSAGE;
        }
        return this.getJsonObject(url, jsonParams);
    }

    /*校验图形验证码并获取短信验证码*/
    @Override
    public BaseResponse<String> getIdentifyingCode(SendMsgCodeRequest sendMsgCodeRequest) {
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(sendMsgCodeRequest));
        String url = "";
        if (InterfaceTypeEnum.HOL.getCode().equals(projectSource)) {
            log.info("进入互联网医院，验证图形验证码，发送短信验证码");
            String imgCode = redisUtil.get(sendMsgCodeRequest.getPhoneNo() + "_verifyCode");
            if (!StringUtils.isEmpty(imgCode) && imgCode.toUpperCase().equals(sendMsgCodeRequest.getVerifyCode().toUpperCase())) {//获取到的缓存图形验证码不为空且和传入的码相同
                url = Constants.HOL_FAMILY_URL + Constants.SENT_SMS_CODE;
                JSONObject jsonReqParams = new JSONObject();
                jsonReqParams.put("mobile", jsonParams.remove("phoneNo"));
                jsonReqParams.put("userType", 1);
                jsonParams = jsonReqParams;
            } else {
                return BaseRespUtil.setResultError("图形验证码错误");
            }
        } else if (InterfaceTypeEnum.GOL.getCode().equals(sendMsgCodeRequest.getType())) {
            log.info("进入健康通，验证图形验证码并发送短信验证码");
            url = Constants.GOL_FAMILY_URL + Constants.GET_CODE;
        }
        return this.getJsonObject(url, jsonParams);
    }


    /*校验短信验证码*/
    @Override
    public BaseResponse<String> validateCode(SendMsgCodeRequest sendMsgCodeRequest) {
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(sendMsgCodeRequest));
        String url = "";
        if (InterfaceTypeEnum.HOL.getCode().equals(sendMsgCodeRequest.getType())) {
            log.info("进入互联网医院，验证短信验证码");
            url = Constants.HOL_FAMILY_URL + Constants.VERIFY_SMS_CODE;
            /*参数转换*/
            JSONObject jsonReqParams = new JSONObject();
            jsonReqParams.put("mobile", jsonParams.remove("phoneNo"));
            jsonReqParams.put("code", jsonParams.remove("identifyingCode"));
            jsonReqParams.put("userType", 1);
            jsonParams = jsonReqParams;
        } else if (InterfaceTypeEnum.GOL.getCode().equals(sendMsgCodeRequest.getType())) {
            log.info("进入健康通，验证短信验证码");
            url = Constants.GOL_FAMILY_URL + Constants.VALIDATE_CODE;
        }
        return this.getJsonObject(url, jsonParams);
    }

    @Override
    public BaseResponse<String> getJsonObject(String url, JSONObject jsonParams) {
        BaseResponse<String> result = new BaseResponse();
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
//        String json = "{\"code\":\"200\",\"message\":\"短线发送成功\"}";
//        JSONObject jsonObject = JSONObject.parseObject(json);
        log.info("JsonObject==" + jsonObject.toJSONString());
        log.info("JsonObject==" + jsonObject.toJSONString());
        if (CommonUtils.isEmpty(jsonObject)) {
            if (InterfaceTypeEnum.GOL.getCode().equals(projectSource)) {
                String code = redisUtil.get(jsonParams.get("msgId").toString()).toString();
                if (CommonUtils.isNotEmpty(code)) {
                    int status = Integer.parseInt(code);
                    if (ResultCode.SUCCESS == status) {
                        result.setCode(ResultCode.SUCCESS);
                        result.setMessage("推送成功");
                        return result;
                    }
                } else {
                    result.setCode(ResultCode.ERROR);
                    result.setMessage("访问超时");
                }
            }
            if (InterfaceTypeEnum.HOL.getCode().equals(projectSource)) {
                //todo 互联网医院
                result.setCode(ResultCode.ERROR);
                result.setMessage("访问超时");
            }

        }
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS) {
                result.setCode(ResultCode.SUCCESS);
                result.setMessage(jsonObject.getString("message"));
            } else {
                result.setCode(ResultCode.ERROR);
                result.setMessage(jsonObject.getString("message"));
            }
        } catch (Exception e) {
            result.setMessage("推送消息失敗" + e.getMessage());
            result.setCode(Constants.ERR_CODE);
        }

        log.info("result:{}", result);
        return result;
    }


    /**
     * 各个业务之间的消息推送
     *
     * @param jsonObject
     * @param status
     * @param msgType
     * @return
     */
    @RpcService
    @Override
    public boolean sendMessage(Object jsonObject, boolean status, int msgType) {
        boolean flag = false;
        String content = "";
        if (InterfaceTypeEnum.HOL.getCode().equals(projectSource)) {
            if (1 == msgType) {  //1  入组审核
                if (status) { //审核通过
                    FusTeamChronicGroupRecordEntity entity = JSONObject.parseObject(jsonObject.toString(), FusTeamChronicGroupRecordEntity.class);
                    SendMsgRequest sendMsgRequest = new SendMsgRequest();
                    sendMsgRequest.setHospitalCode(entity.getOrganizationId());
                    sendMsgRequest.setBusinessType(204);
                    sendMsgRequest.setUserType(1);
                    sendMsgRequest.setPatientIdentityCardType(entity.getCardType());
                    sendMsgRequest.setPatientIdentityCardNumber(entity.getCardNumber());
                    List<MsgVariable> list = new ArrayList<>();
                    MsgVariable msgVariable = new MsgVariable();
                    msgVariable.setMsgVariableKey("【患者姓名】");
                    msgVariable.setMsgVariableValue(entity.getApplyPersonName());
                    list.add(msgVariable);
                    MsgVariable msgVariable1 = new MsgVariable();
                    msgVariable1.setMsgVariableKey("【申请时间】");
                    msgVariable1.setMsgVariableValue(DateUtil.format3.format(entity.getApplyTime()));
                    list.add(msgVariable1);
                    MsgVariable msgVariable2 = new MsgVariable();
                    msgVariable2.setMsgVariableKey("【科室名称】");
                    msgVariable2.setMsgVariableValue(entity.getDepartmentName());
                    list.add(msgVariable2);
                    MsgVariable msgVariable3 = new MsgVariable();
                    msgVariable3.setMsgVariableKey("【慢病种类】");
                    msgVariable3.setMsgVariableValue(entity.getChronicDiseaseName());
                    list.add(msgVariable3);
                    MsgVariable msgVariable4 = new MsgVariable();
                    msgVariable4.setMsgVariableKey("【主管医生姓名】");
                    msgVariable4.setMsgVariableValue(entity.getDoctorName());
                    list.add(msgVariable4);
                    MsgVariable msgVariable5 = new MsgVariable();
                    msgVariable5.setMsgVariableKey("teamChronicGroupId");
                    msgVariable5.setMsgVariableValue(entity.getTeamChronicGroupId() + "");
                    list.add(msgVariable5);
                    sendMsgRequest.setMsgVariableList(list);
                    this.productionMessage(sendMsgRequest);
                    flag = true;
                } else {//审核不通过
                    FusTeamChronicGroupRecordEntity entity = JSONObject.parseObject(jsonObject.toString(), FusTeamChronicGroupRecordEntity.class);
                    SendMsgRequest sendMsgRequest = new SendMsgRequest();
                    sendMsgRequest.setHospitalCode(entity.getOrganizationId());
                    sendMsgRequest.setBusinessType(205);
                    sendMsgRequest.setUserType(1);
                    sendMsgRequest.setPatientIdentityCardType(entity.getCardType());
                    sendMsgRequest.setPatientIdentityCardNumber(entity.getCardNumber());
                    List<MsgVariable> list = new ArrayList<>();
                    MsgVariable msgVariable = new MsgVariable();
                    msgVariable.setMsgVariableKey("【患者姓名】");
                    msgVariable.setMsgVariableValue(entity.getApplyPersonName());
                    list.add(msgVariable);
                    MsgVariable msgVariable1 = new MsgVariable();
                    msgVariable1.setMsgVariableKey("【申请时间】");
                    msgVariable1.setMsgVariableValue(DateUtil.format3.format(entity.getApplyTime()));
                    list.add(msgVariable1);
                    MsgVariable msgVariable2 = new MsgVariable();
                    msgVariable2.setMsgVariableKey("【科室名称】");
                    msgVariable2.setMsgVariableValue(entity.getDepartmentName());
                    list.add(msgVariable2);
                    MsgVariable msgVariable3 = new MsgVariable();
                    msgVariable3.setMsgVariableKey("【慢病种类】");
                    msgVariable3.setMsgVariableValue(entity.getChronicDiseaseName());
                    list.add(msgVariable3);
                    MsgVariable msgVariable4 = new MsgVariable();
                    msgVariable4.setMsgVariableKey("【审核意见】");
                    msgVariable4.setMsgVariableValue(entity.getAuditOpinion());
                    list.add(msgVariable4);
                    MsgVariable msgVariable5 = new MsgVariable();
                    msgVariable5.setMsgVariableKey("teamChronicGroupId");
                    msgVariable5.setMsgVariableValue(entity.getTeamChronicGroupId() + "");
                    list.add(msgVariable5);
                    sendMsgRequest.setMsgVariableList(list);
                    this.productionMessage(sendMsgRequest);
                    flag = true;
                }
                return flag;
            } else if (2 == msgType) { //随访任务通知
                FollowUpRecordsMessageVO entity = JSONObject.parseObject(jsonObject.toString(), FollowUpRecordsMessageVO.class);
                SendMsgRequest sendMsgRequest = new SendMsgRequest();
                sendMsgRequest.setHospitalCode(entity.getOrganizationId());
                sendMsgRequest.setBusinessType(203);
                sendMsgRequest.setUserType(1);
                sendMsgRequest.setPatientIdentityCardType(entity.getCardType());
                sendMsgRequest.setPatientIdentityCardNumber(entity.getCardNumber());
                List<MsgVariable> list = new ArrayList<>();
                MsgVariable msgVariable = new MsgVariable();
                msgVariable.setMsgVariableKey("【患者姓名】");
                msgVariable.setMsgVariableValue(entity.getPatientName());
                list.add(msgVariable);
                MsgVariable msgVariable1 = new MsgVariable();
                msgVariable1.setMsgVariableKey("【随访事件执行日期】");
                msgVariable1.setMsgVariableValue(DateUtil.format3.format(entity.getPlanNotifyDate()));
                list.add(msgVariable1);
                MsgVariable msgVariable2 = new MsgVariable();
                msgVariable2.setMsgVariableKey("【随访类型名称】");
                msgVariable2.setMsgVariableValue(entity.getRouteName());
                list.add(msgVariable2);
                MsgVariable msgVariable3 = new MsgVariable();
                msgVariable3.setMsgVariableKey("cardType");
                msgVariable3.setMsgVariableValue(entity.getCardType());
                list.add(msgVariable3);
                MsgVariable msgVariable4 = new MsgVariable();
                msgVariable4.setMsgVariableKey("cardNo");
                msgVariable4.setMsgVariableValue(entity.getCardNumber());
                list.add(msgVariable4);
                sendMsgRequest.setMsgVariableList(list);
                this.productionMessage(sendMsgRequest);
                flag = true;
            } else if (3 == msgType) {//短信
                FusTeamChronicGroupRecordEntity entity = JSONObject.parseObject(jsonObject.toString(), FusTeamChronicGroupRecordEntity.class);
                SendMsgRequest sendMsgRequest = new SendMsgRequest();
                sendMsgRequest.setHospitalCode(entity.getOrganizationId());
                sendMsgRequest.setBusinessType(206);
                sendMsgRequest.setUserType(1);
                sendMsgRequest.setMobile(entity.getTelephone());
                sendMsgRequest.setPatientIdentityCardType(entity.getCardType());
                sendMsgRequest.setPatientIdentityCardNumber(entity.getCardNumber());
                List<MsgVariable> list = new ArrayList<>();
                MsgVariable msgVariable = new MsgVariable();
                msgVariable.setMsgVariableKey("【患者姓名】");
                msgVariable.setMsgVariableValue(entity.getPersonName());
                list.add(msgVariable);
                MsgVariable msgVariable1 = new MsgVariable();
                msgVariable1.setMsgVariableKey("【医院名称】");
                msgVariable1.setMsgVariableValue(entity.getOrganizationName());
                list.add(msgVariable1);
                MsgVariable msgVariable3 = new MsgVariable();
                msgVariable3.setMsgVariableKey("【慢病种类】");
                msgVariable3.setMsgVariableValue(entity.getChronicDiseaseName());
                list.add(msgVariable3);
                sendMsgRequest.setMsgVariableList(list);
                this.productionMessage(sendMsgRequest);
                flag = true;
            }
        } else if (InterfaceTypeEnum.GOL.getCode().equals(projectSource)) {
            if (1 == msgType) {  //1  入组审核
                FusTeamChronicGroupRecordEntity entity = JSONObject.parseObject(jsonObject.toString(), FusTeamChronicGroupRecordEntity.class);
                PushMessageRequest pushMessageRequest = new PushMessageRequest();
                pushMessageRequest.setMsgId(UUID.randomUUID().toString());
                if (status) { //审核通过
                    ContextUtils.put(Context.TENANT_ID, tanlentId);
                    pushMessageRequest.setTemplateCode("FOLLOW_UP_APPROVED");
                    pushMessageRequest.setNotificateType("follow_up_approved");
                    pushMessageRequest.setRoleId("patient");
                    pushMessageRequest.setPatientIdentityCardType(entity.getCardType());
                    pushMessageRequest.setPatientIdentityCardNumber(SM4Utils.encryptData_ECB(entity.getCardNumber()));
                    pushMessageRequest.setPatientMedicalCardType(entity.getPatientMedicalCardType());
                    pushMessageRequest.setPatientMedicalCardNumber(SM4Utils.encryptData_ECB(entity.getPatientMedicalCardNumber()));
                    Certificate certificate = new Certificate(entity.getCardType(), SM4Utils.encryptData_ECB(entity.getCardNumber()), "01");
                    String mpiId = null;
                    try {
                        mpiId = mpiProvider.getMpiIdByCertificate(certificate);
                    } catch (MPIException e) {
                        e.printStackTrace();
                    }
                    Map<String, String> variableMap = new HashMap<>();
                    variableMap.put("jiguang", "极光消息");
                    variableMap.put("#患者姓名#", entity.getApplyPersonName());
                    variableMap.put("#申请时间#", DateUtil.format3.format(entity.getApplyTime()));
                    variableMap.put("#慢病种类#", entity.getChronicDiseaseName());
                    variableMap.put("#主管医生姓名#", entity.getDoctorName());

                    Map<String, String> extraMap = new HashMap<>();
                    extraMap.put("teamChronicGroupId", entity.getTeamChronicGroupId() + "");
                    extraMap.put("mpiId", mpiId);
                    pushMessageRequest.setExtras(extraMap);
                    //微信公众号必要入参
                    String userId=queryUserId(pushMessageRequest.getPatientIdentityCardType(),pushMessageRequest.getPatientIdentityCardNumber());
                    AccessToken accessToken=null;
                    try {
//                        String  url = followUpDistUrl + "#/slowDiseaseManagement/MyApplicationList?sparamstr={\"bussType\":\"" + projectSource + "\",\"source\":\"3\"," +
//                                "\"userId\":\"" + userId + "\",\"patientId\":\""+entity.getPatientId()+"\"}";
                        String jumpUrl = followUpDistUrl + "/#/pages/packageIndex/wxMessageEntry/index?sparamstr={\"source\":\"3\",\"userId\":\""+
                                userId+"\",\"path\":\"/pages/packageSpecialDisease/application/myApplicationList\"} ";
                                //获取居民token
//                        accessToken= findUserTokenByUserId(userId);
//                        if(CommonUtils.isNotEmpty(accessToken)){
//                            jumpUrl = followUpDistUrl + "#/slowDiseaseManagement/MyApplicationList?sparamstr={\"bussType\":\"" + projectSource + "\",\"source\":\"3\"," +
//                                    "\"userId\":\"" + userId + "\",\"patientId\":\""+entity.getPatientId()+"\",\"accessToken\":\""+accessToken.getId()+"\"}";
//                        }
                        variableMap.put("#jumpUrl#",jumpUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.info("通过userId获取tocken异常：" + e.getMessage());
                    }
                    pushMessageRequest.setMsgVariableMap(variableMap);

                } else {//审核不通过
                    pushMessageRequest.setTemplateCode("FOLLOW_UP_AUDIT_NO_PASS");
                    pushMessageRequest.setNotificateType("follow_up_audit_no_pass");
                    pushMessageRequest.setRoleId("patient");

                    pushMessageRequest.setPatientIdentityCardType(entity.getCardType());
                    pushMessageRequest.setPatientIdentityCardNumber(SM4Utils.encryptData_ECB(entity.getCardNumber()));
                    pushMessageRequest.setPatientMedicalCardType(entity.getPatientMedicalCardType());
                    pushMessageRequest.setPatientMedicalCardNumber(SM4Utils.encryptData_ECB(entity.getPatientMedicalCardNumber()));

                    Map<String, String> variableMap = new HashMap<>();
                    variableMap.put("jiguang", "极光消息");
                    variableMap.put("#患者姓名#", entity.getApplyPersonName());
                    variableMap.put("#申请时间#", DateUtil.format3.format(entity.getApplyTime()));
                    variableMap.put("#慢病种类#", entity.getChronicDiseaseName());
                    variableMap.put("#审核意见#", entity.getAuditOpinion());

                    Map<String, String> extraMap = new HashMap<>();
                    extraMap.put("teamChronicGroupId", entity.getTeamChronicGroupId() + "");
                    pushMessageRequest.setExtras(extraMap);
                    //微信公众号必要入参
                    String userId=queryUserId(pushMessageRequest.getPatientIdentityCardType(),pushMessageRequest.getPatientIdentityCardNumber());
                    AccessToken accessToken=null;
                    try {
//                        String  url = followUpDistUrl + "#/slowDiseaseManagement/MyApplicationList?sparamstr={\"bussType\":\"" + projectSource + "\",\"source\":\"3\"," +
//                                "\"userId\":\"" + userId + "\",\"patientId\":\""+entity.getPatientId()+"\"}";
//                        //获取居民token
//                        accessToken= findUserTokenByUserId(userId);
//                        if(CommonUtils.isNotEmpty(accessToken)){
//                            url = followUpDistUrl + "#/slowDiseaseManagement/MyApplicationList?sparamstr={\"bussType\":\"" + projectSource + "\",\"source\":\"3\"," +
//                                    "\"userId\":\"" + userId + "\",\"patientId\":\""+entity.getPatientId()+"\",\"accessToken\":\""+accessToken.getId()+"\"}";
//                        }
                        String jumpUrl = followUpDistUrl + "/#/pages/packageIndex/wxMessageEntry/index?sparamstr={\"source\":\"3\",\"userId\":\""+
                                userId+"\",\"path\":\"/pages/packageSpecialDisease/application/myApplicationList\"} ";
                        variableMap.put("#jumpUrl#",jumpUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.info("通过userId获取tocken异常：" + e.getMessage());
                    }
                    pushMessageRequest.setMsgVariableMap(variableMap);

                }
                this.pushNewMessage(pushMessageRequest);
                flag = true;

            } else if (2 == msgType) {//随访任务通知
                FollowUpRecordsMessageVO entity = JSONObject.parseObject(jsonObject.toString(), FollowUpRecordsMessageVO.class);
                PushMessageRequest pushMessageRequest = new PushMessageRequest();
                pushMessageRequest.setTemplateCode("FOLLOW_UP_TASK_NOTICE");
                pushMessageRequest.setNotificateType("follow_up_task_notice");
                pushMessageRequest.setRoleId("patient");
                ContextUtils.put(Context.TENANT_ID, tanlentId);
                pushMessageRequest.setPatientIdentityCardType(entity.getCardType());
                pushMessageRequest.setPatientIdentityCardNumber(SM4Utils.encryptData_ECB(entity.getCardNumber()));
                pushMessageRequest.setPatientMedicalCardType(entity.getPatientMedicalCardType());
                pushMessageRequest.setPatientMedicalCardNumber(SM4Utils.encryptData_ECB(entity.getPatientMedicalCardNumber()));
                Certificate certificate = new Certificate(entity.getCardType(), SM4Utils.encryptData_ECB(entity.getCardNumber()), "01");
                String mpiId = null;
                try {
                    mpiId = mpiProvider.getMpiIdByCertificate(certificate);
                } catch (MPIException e) {
                    e.printStackTrace();
                }
                Map<String, String> variableMap = new HashMap<>();
                variableMap.put("jiguang", "极光消息");
                variableMap.put("#患者姓名#", entity.getPatientName());
                variableMap.put("#随访事件执行日期#", DateUtil.format3.format(entity.getPlanNotifyDate()));
                if (CommonUtils.isNotEmpty(entity.getRouteName())){
                    variableMap.put("#随访类型名称#", entity.getRouteName());
                }else {
                    variableMap.put("#随访类型名称#","");
                }
                variableMap.put("#医生姓名#", entity.getDoctorName());
                if (CommonUtils.isNotEmpty(entity.getRecordId())){
                    FollowUpRecordsRequisition fQuery = new FollowUpRecordsRequisition();
                    fQuery.setRecordId(entity.getRecordId());
                    List<FollowUpRecordsRequisition> requisitions = followUpRecordsRequisitionDAO.selectList(fQuery);
                    if (CommonUtils.isNotEmpty(requisitions)){
                        variableMap.put("#随访内容#", requisitions.get(0).getQuestionnaireName());
                    }else {
                        variableMap.put("#随访内容#", "");
                    }
                }else {
                    variableMap.put("#随访内容#", "");
                }
                variableMap.put("#personId#", mpiId);
                variableMap.put("#创业慧康智慧医院#", organizationRpcService.getOrgNameByOrgCode(entity.getOrganizationId()));
                pushMessageRequest.setMsgVariableMap(variableMap);

                Map<String, String> extraMap = new HashMap<>();
                extraMap.put("cardType", entity.getCardType());
                extraMap.put("cardNo", entity.getCardNumber());
                extraMap.put("mpiId", mpiId);
                pushMessageRequest.setExtras(extraMap);
                //微信公众号必要入参
                String userId=queryUserId(pushMessageRequest.getPatientIdentityCardType(),pushMessageRequest.getPatientIdentityCardNumber());
                AccessToken accessToken=null;
                try {
                    String  url = followUpDistUrl + "#/slowDiseaseManagement/myTask?sparamstr={\"bussType\":\"" + projectSource + "\",\"source\":\"3\"," +
                            "\"userId\":\"" + userId + "\",\"cardType\":\""+entity.getCardType()+"\",\"cardNo\":\""+entity.getCardNumber()+"\"}";
                    //获取居民token
                    accessToken= findUserTokenByUserId(userId);
                    if(CommonUtils.isNotEmpty(accessToken)){
                        url = followUpDistUrl + "#/slowDiseaseManagement/myTask?sparamstr={\"bussType\":\"" + projectSource + "\",\"source\":\"3\"," +
                                "\"userId\":\"" + userId + "\",\"cardType\":\""+entity.getCardType()+"\",\"cardNo\":\""+entity.getCardNumber()+"\",\"accessToken\":\""+accessToken+"\"}";
                    }
                    variableMap.put("#jumpUrl#",url);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("通过userId获取tocken异常：" + e.getMessage());
                }
                this.pushNewMessage(pushMessageRequest);
                flag = true;
            } else if (3 == msgType) {//短信
                FusTeamChronicGroupRecordEntity entity = JSONObject.parseObject(jsonObject.toString(), FusTeamChronicGroupRecordEntity.class);

                PushMessageRequest pushMessageRequest = new PushMessageRequest();
                pushMessageRequest.setTemplateCode("JOIN_CHRONICDISEASE_MANAGETEAMSUCCESS");
                pushMessageRequest.setRoleId("patient");
                pushMessageRequest.setMobile(entity.getTelephone());

                Map<String, String> variableMap = new HashMap<>();
                variableMap.put("duanxin", "短信");
                variableMap.put("#患者姓名#", entity.getPersonName());
                variableMap.put("#医院名称#", entity.getOrganizationName());
                variableMap.put("#慢病种类#", entity.getChronicDiseaseName());
                pushMessageRequest.setMsgVariableMap(variableMap);

                this.pushNewMessage(pushMessageRequest);
                flag = true;
            }
        }


        return flag;
    }

    private String queryUserId(String cardType,String cardId){
        Certificate certificate = null;
        String userId=null;
        try {
            if(CommonUtils.isNotEmpty(cardType)&&CommonUtils.isNotEmpty(cardId)){
                certificate = new Certificate(IdentityTransformUtil.huLianIdentityToHcn(cardType), cardId, "01");
                if (hcn.util.CommonUtils.isNotNull(certificate)) {
                    Unique unique = mpiProvider.getUnique(certificate, hcn.common.Constants.USERID_SOURCE, hcn.common.Constants.USERID_TYPE_CODE);
                    if (null != unique) {
                         userId = SM4Utils.decryptData_ECB(unique.getUniqueId());
                     }
                   }
                }
        } catch (MPIException e) {
            log.error("queryUserId出错:"+e.getMessage());
            e.printStackTrace();
        }
        return userId;
    }
    public AccessToken findUserTokenByUserId(String userId) {
        List<UserRoleToken> rs = null;
        AccessToken  accessToken =null;
        try {
            User user= AccountCenter.getUser(userId);
            if(CommonUtils.isNotEmpty(user)){
                Collection<UserRoleToken> tokens = user.getUserRoleTokens();
                rs = new ArrayList();
                Iterator var4 = tokens.iterator();

                while(var4.hasNext()) {
                    UserRoleToken ur = (UserRoleToken)var4.next();
                    rs.add(ur);
                }
                if(CommonUtils.isNotEmpty(rs)){
                    accessToken= AppContextHolder.get().getBean(AccessTokenLoader.class).getByUser(rs.get(0).getUserId(),rs.get(0).getId(),rs.get(0).getDeptId());
                }
            }
        } catch (ControllerException e) {
            e.printStackTrace();
        }

        return accessToken;
    }

    /**
     * @Describe: 消息推送
     * @Param: [pushMessageBean]
     * @Return: void
     * @Author: zhengcb10708
     * @Date: 2021/5/14 11:30
     */
    @Override
    public void productionMessage(PushMessageBean pushMessageBean) throws Exception {
        Client.rpcInvoke("hcn.messageSyncService","productionMessage",pushMessageBean);
    }

}
